const fs = require('fs')
const express = require('express');
const { apiPath } = require('../../lib/api-path')

const router = express.Router();

function getRoutes() {
  const path = apiPath
  const stat = dirExit(path)
  if (!stat) {
    console.log('path undefine ', path)
    return
  }
  console.log('进来啦, path=', path, stat)

  if (stat.isDirectory()) {
    console.log('进入循环')
    dirForEach(path, (routers) => {
      console.log('routers=>', routers)
      const entry = routers.entry
      const entryTouter = routers.entryRouter
      const routerFn = require(entryTouter).default
      router.use(entry, routerFn)
    })
  }
  return router
}

const fileTypes = /\.js$/; // 只匹配以js结尾的文件
function dirForEach(path, callback, dirPath = '') {
  fs.readdirSync(path).forEach(file => {
    console.log('file=>', file)
    if (fileTypes.test(file) > 0) {
      console.log('file true--------')
      const fullPath = path + '/' + file
      const fileInfo = fs.statSync(fullPath)
      if (fileInfo.isFile()) {
        console.log('isFile')
        const entryPrefix = dirPath ? dirPath : ''
        const endPoint = file.indexOf('.js')
        const entry = entryPrefix + '/' + file.substring(0, endPoint)
        const entryRouter = fullPath
        const obj = { entry, entryRouter }
        callback && callback(obj)
      } else if (fileInfo.isDirectory()) {
        console.log('isDirectory')
        let entryPrefix = dirPath ? '/' + dirPath : ''
        entryPrefix = entryPrefix + '/' + file
        return dirForEach(path, callback, entryPrefix)
      }
    }
  })
}

function dirExit(path) {
  let stat = null
  try {
    const fileStat = fs.statSync(path)
    if (fileStat) {
      stat = fileStat
    }
  } catch (error) {
    stat = null
  }
  return stat
}

module.exports = getRoutes